package Test;


import com.alibaba.fastjson.JSONObject;
import ecode.security.rsa.Base64;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.OnLineMonitor;
import weaver.hrm.User;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.IOException;
import java.io.StringReader;
import java.security.Key;
import java.util.HashMap;
import java.util.Map;

public class LoginOA extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        doGet(req, res);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        BaseBean bb = new BaseBean();
        bb.writeLog("---LoginOA---");
        String identity_token = req.getParameter("Identity_Token");
        bb.writeLog("---LoginOA---token：" + identity_token);
        if (identity_token.length() > 150) {
            System.out.println(identity_token);
            String ssoxml = des3Decode(identity_token);
            Map<String, String> acountByToken = getAcountByToken(ssoxml);
            String username = acountByToken.get("username");
            bb.writeLog("----密钥是：：" + identity_token);
            bb.writeLog("用户名：：" + username);
            JSONObject json = new JSONObject();
            json.put("login", username);
            json.put("isSucceed", "1");
            Cookie cookie = new Cookie("UserInfo", json.toJSONString());
            res.addCookie(cookie);
        } else {
            bb.writeLog("---LoginOA---执行跳转：" + identity_token);
            String userstr = des3Decode0(identity_token);
            String username = userstr.substring(userstr.indexOf(":") + 1, userstr.indexOf(","));
            bb.writeLog("当前登录人的用户名：：" + username);
            boolean flag = LoginUsername(username, req, res);
            bb.writeLog("认证结果是：：" + flag);
            res.sendRedirect("http://180.101.128.124:7172/spa/em/mobile.html");
        }
    }

    /**
     * @param str 参数 长token
     * @return 解密后的数据  xml格式
     */
    public String des3Decode(String str) {
        String deString = null;
        byte[] test1 = Base64.decodeBase64(str);
        try {
            //CBC 解密
            byte[] str1 = des3DecodeCBC(test1);
            deString = new String(str1, "UTF-8");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return deString;
    }

    public byte[] des3DecodeCBC(byte[] data) throws Exception {
        byte[] key = "1qaz2wsx3edc4rfv5tgb6yhn".getBytes("UTF-8");
        byte[] keyiv = "sin0opec".getBytes("UTF-8");
        Key deskey = null;
        DESedeKeySpec spec = new DESedeKeySpec(key);
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
        deskey = keyfactory.generateSecret(spec);
        Cipher cipher = Cipher.getInstance("DESede" + "/CBC/PKCS5Padding");
        IvParameterSpec ips = new IvParameterSpec(keyiv);
        cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
        byte[] bOut = cipher.doFinal(data);
        return bOut;
    }

    /**
     * @param key xml格式的数据
     * @return map格式的数据
     */
    public Map<String, String> getAcountByToken(String key) {
        String keyxml = getAcountxml(key);
        return parseUsernameAndPsd(keyxml);
    }

    /**
     * @param keyxml xml格式的 数据
     * @return map格式的数据
     */
    private Map<String, String> parseUsernameAndPsd(String keyxml) {
        Map<String, String> keymap = new HashMap<String, String>();
        String username = "";
        String password = "";
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse(new InputSource(new StringReader(keyxml)));
            NodeList employees = document.getElementsByTagName("Attribute");
            for (int i = 0; i < employees.getLength(); i++) {
                Node node = employees.item(i);
                NamedNodeMap NodeMap = node.getAttributes();
                String value = NodeMap.getNamedItem("Name").getNodeValue();
//                System.out.println(value);
                if ("UserId".equals(value)) {
                    username = node.getTextContent().trim();
                } else if ("Password".equals(value)) {
                    password = node.getTextContent().trim();
                }
            }
            System.out.println("ceshi user: " + username + " password:" + password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        keymap.put("username", username);
        keymap.put("password", password);
        return keymap;
    }

    /**
     * @param keyxml 处理xml格式的数据
     * @return xml格式数据
     */
    private String getAcountxml(String keyxml) {
        int beginIndex = keyxml.indexOf("<AttributeStatement>");
        int endIndex = keyxml.indexOf("</AttributeStatement>");
        keyxml = keyxml.substring(beginIndex, endIndex);
        keyxml = keyxml + "</AttributeStatement>";
        return keyxml;
    }

    /**
     * @param str 解密短token
     * @return 解密后的数据 字符串
     */
    public String des3Decode0(String str) {
        String deString = null;
        byte[] test1 = Base64.decodeBase64(str);
        try {
            //CBC 解密
            byte[] str1 = des3DecodeCBC0(test1);
            deString = new String(str1, "UTF-8");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return deString;
    }

    /**
     * @param data 解密短token
     * @return
     * @throws Exception
     */
    public byte[] des3DecodeCBC0(byte[] data) throws Exception {
        byte[] key0 = "0okm9ijn8uhb7ygv6tfc5rdx".getBytes("UTF-8");
        byte[] keyiv0 = "sin0opec".getBytes("UTF-8");
        Key deskey = null;
        DESedeKeySpec spec = new DESedeKeySpec(key0);
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
        deskey = keyfactory.generateSecret(spec);
        Cipher cipher = Cipher.getInstance("DESede" + "/CBC/PKCS5Padding");
        IvParameterSpec ips = new IvParameterSpec(keyiv0);
        cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
        byte[] bOut = cipher.doFinal(data);
        return bOut;

    }

    /**
     * 验证用户登录的
     *
     * @param username 用户登录名
     * @param request  request
     * @param response response
     * @return 是否登录成功
     * @throws IOException
     */
    public boolean LoginUsername(String username, HttpServletRequest request, HttpServletResponse response) throws IOException {
        RecordSet rs = new RecordSet();
        rs.execute("select * from HrmResource where loginid='" + username + "'");
        BaseBean bb = new BaseBean();
        bb.writeLog("select * from HrmResource where loginid='" + username + "'");
        if (rs.next()) {
            bb.writeLog("判断是否有数据'" + username + "'");
            User user = new User();
            user.setUid(rs.getInt("id"));
            user.setLoginid(rs.getString("loginid"));
            user.setFirstname(rs.getString("firstname"));
            user.setLastname(rs.getString("lastname"));
            user.setAliasname(rs.getString("aliasname"));
            user.setTitle(rs.getString("title"));
            user.setTitlelocation(rs.getString("titlelocation"));
            user.setSex(rs.getString("sex"));
            user.setPwd(rs.getString("password"));
            String languageidweaver = rs.getString("systemlanguage");
            user.setLanguage(Util.getIntValue(languageidweaver, 0));

            user.setTelephone(rs.getString("telephone"));
            user.setMobile(rs.getString("mobile"));
            user.setMobilecall(rs.getString("mobilecall"));
            user.setEmail(rs.getString("email"));
            user.setCountryid(rs.getString("countryid"));
            user.setLocationid(rs.getString("locationid"));
            user.setResourcetype(rs.getString("resourcetype"));
            user.setStartdate(rs.getString("startdate"));
            user.setEnddate(rs.getString("enddate"));
            user.setContractdate(rs.getString("contractdate"));
            user.setJobtitle(rs.getString("jobtitle"));
            user.setJobgroup(rs.getString("jobgroup"));
            user.setJobactivity(rs.getString("jobactivity"));
            user.setJoblevel(rs.getString("joblevel"));
            user.setSeclevel(rs.getString("seclevel"));
            user.setUserDepartment(Util.getIntValue(rs.getString("departmentid"), 0));
            user.setUserSubCompany1(Util.getIntValue(rs.getString("subcompanyid1"), 0));
            user.setUserSubCompany2(Util.getIntValue(rs.getString("subcompanyid2"), 0));
            user.setUserSubCompany3(Util.getIntValue(rs.getString("subcompanyid3"), 0));
            user.setUserSubCompany4(Util.getIntValue(rs.getString("subcompanyid4"), 0));
            user.setManagerid(rs.getString("managerid"));
            user.setAssistantid(rs.getString("assistantid"));
            user.setPurchaselimit(rs.getString("purchaselimit"));
            user.setCurrencyid(rs.getString("currencyid"));
            user.setLastlogindate(rs.getString("currentdate"));
            user.setLogintype("1");
            user.setAccount(rs.getString("account"));

            user.setLoginip(request.getRemoteAddr());
            request.getSession(true).setMaxInactiveInterval(60 * 60 * 24);
            request.getSession(true).setAttribute("weaver_user@bean", user);
            request.getSession(true).setAttribute("moniter", new OnLineMonitor("" + user.getUID(), user.getLoginip()));
            Util.setCookie(response, "loginfileweaver", "/main.jsp", 172800);
            Util.setCookie(response, "loginidweaver", "" + user.getUID(), 172800);
            Util.setCookie(response, "languageidweaver", languageidweaver, 172800);
            weaver.systeminfo.template.UserTemplate ut = new weaver.systeminfo.template.UserTemplate();
            ut.getTemplateByUID(user.getUID(), user.getUserSubCompany1());
            String defaultHp = ut.getDefaultHp();
            HttpSession session = request.getSession();
            ServletContext application = getServletContext();
            session.setAttribute("defaultHp", defaultHp);
            Map logmessages = (Map) application.getAttribute("logmessages");
            if (logmessages == null) {
                logmessages = new HashMap();
                logmessages.put("" + user.getUID(), "");
                application.setAttribute("logmessages", logmessages);
            }

            session.setAttribute("logmessage", "");
            return true;
        }
        return false;
    }

}